#! /bin/bash
# chkconfig: 2345 55 25
# Description: Startup script for Game-Server(XiaoBao) on Debian. Place in /etc/init.d and
# run 'update-rc.d -f game-server defaults', or use the appropriate command on your
# distro. For CentOS/Redhat run: 'chkconfig --add game-server'

### BEGIN INIT INFO
# Provides:          game-server
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the game-server
# Description:       starts game-server using start-stop
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
ProgramName="Game-Server(XiaoBao)"
ProgramPath="/usr/local/game-server"
NAME=game-server
BIN=${ProgramPath}/$NAME
CONFIGFILE=${ProgramPath}/config.json
LOGFILE=${ProgramPath}/game-server.log
SCRIPTNAME=/etc/init.d/$NAME
program_version=`${BIN} -version`
version="1.2"
RET_VAL=0

[ -x $BIN ] || exit 0

fun_check_run()
{
    PID=`ps -ef | grep -v grep | grep -i "${BIN}" | awk '{print $2}'`
    if [ ! -z $PID ]; then
        return 0
    else
        return 1
    fi
}
fun_load_config(){
    if [ ! -r ${CONFIGFILE} ]; then
        echo "config file ${CONFIGFILE} not found"
        return 1
    fi
}
fun_status()
{
    PID=`ps -ef | grep -v grep | grep -i "${BIN}" | awk '{print $2}'`
    if [ ! -z $PID ]; then
        echo "${ProgramName} (pid $PID) is running..."
    else
        echo "${ProgramName} is stopped"
        exit 0
    fi
}
fun_start(){
    if fun_check_run; then
        echo "${ProgramName} (pid $PID) already running."
        return 0
    fi
    fun_load_config
    echo -n "Starting ${ProgramName}..."
    ${BIN} -c ${CONFIGFILE} > ${LOGFILE} 2>&1 &
    sleep 1
    if ! fun_check_run; then
        echo "start failed"
        return 1
    fi
    echo " done"
    echo "${ProgramName} (pid $PID)is running."
    echo "read ${LOGFILE} for log"
    return 0
}

fun_stop(){
    if fun_check_run; then
        echo -n "Stoping ${ProgramName} (pid $PID)... "
        kill $PID
        if [ "$?" != 0 ] ; then
            echo " failed"
            return 1
        else
            echo " done"
        fi
    else
        echo "${ProgramName} is not running."
    fi
    return 0
}

fun_restart(){
    fun_stop
    fun_start
}

fun_config(){
    if [ -s ${CONFIGFILE} ]; then
        vi ${CONFIGFILE}
    else
        echo "${ProgramName} configuration file not found!"
        return 1
    fi
}

fun_version(){
    echo "${program_version}"
    return 0
}

case "$1" in
    start|stop|restart|status|version)
        fun_$1
    ;;
    *)
        echo "Usage: $SCRIPTNAME {start|stop|restart|status|version}"
        RET_VAL=1
    ;;
esac
exit $RET_VAL
